<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="queryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="机构名称" prop="organizationName">
        <el-input v-model="queryParams.organizationName" placeholder="请输入机构名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="上线" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择上线" clearable>
          <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="省、市、区" prop="queryProvinceAndCityAndDistrict">
        <el-cascader placeholder="请选择省、市、区" v-model="queryParams.queryProvinceAndCityAndDistrict" :options="options"
          @keyup.enter.native="handleQuery" @lazy-load="selectLoadOptions"
          :props="{ lazy: true,checkStrictly:true,multiple: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }"
          clearable></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['agent:organization:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['agent:organization:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['agent:organization:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="organizationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="机构名称" align="center" prop="organizationName" />
      <el-table-column label="联系电话" align="center" prop="tel" />
      <el-table-column label="省、市、区" align="center" prop="provinceAndCityAndDistrict" />
      <el-table-column label="上线" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="招生人数" align="center" prop="stuCount" />
      <el-table-column label="所属代理" align="center" prop="agentName" />
      <el-table-column label="操作" fixed="right" width="200px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-info" @click="handleDetail(scope.row)"
            v-hasPermi="['agent:organization:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['agent:organization:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['agent:organization:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改机构信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称" prop="organizationName">
              <el-input v-model="form.organizationName" placeholder="请输入机构名称" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线" prop="state">
              <el-select v-model="form.state" placeholder="请选择上线" :disabled="detailView">
                <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招生人数" prop="stuCount">
              <el-input v-model="form.stuCount" placeholder="请输入招生人数" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省、市、区" prop="provinceAndCityAndDistrict">
              <el-cascader placeholder="请选择省、市、区" v-model="form.provinceAndCityAndDistrict" :options="options"
                @lazy-load="selectLoadOptions"
                :props="{ lazy: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }" clearable
                :disabled="detailView"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属代理" prop="agentName">
              <el-input v-model="form.agentName" placeholder="请输入所属代理商" @click.native="openSelectAgent(2)"
                :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一销负责人" prop="firstSaleUser">
              <el-input v-model="form.firstSaleUser" placeholder="请输入一销负责人" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二销负责人" prop="secondSaleUser">
              <el-input v-model="form.secondSaleUser" placeholder="请输入二销负责人" :disabled="detailView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="佣金比例" prop="ratio">
              <el-input v-model="form.ratio" placeholder="请输入佣金比例" :disabled="detailView">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参考价" prop="referencePrice">
              <el-input v-model="form.referencePrice" placeholder="请输入参考价" :disabled="detailView">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构类型" prop="orgType">
              <el-radio-group v-model="form.orgType" size="medium">
                <el-radio-button v-for="dict in dict.type.org_type" :key="dict.value"
                  :label="dict.value">{{dict.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程级别" prop="level">
              <el-checkbox-group v-model="form.level" size="medium">
                <el-checkbox-button v-for="dict in dict.type.level" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs type="border-card" v-if="detailView" @tab-click="handleTabClick">
          <el-tab-pane label="学员"><student-info ref="studentInfo"></student-info></el-tab-pane>
          <el-tab-pane label="校区"><school-info ref="schoolInfo"></school-info></el-tab-pane>
          <el-tab-pane label="操作日志"><field-log ref="fieldLog"></field-log></el-tab-pane>
        </el-tabs>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!detailView" :loading="submitLoading">
          {{ submitLoading ? '提交中...' : '确定' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择代理 -->
    <SelectAgent ref="selectAgent" :open="selectFlag" @selected-data="selectAgentData"
      @close-select-window="closeSelectAgent" />
  </div>
</template>

<script>
  import {
    listOrganization,
    getOrganization,
    delOrganization,
    addOrganization,
    updateOrganization
  } from "@/api/bus_web/agent/organization";
  import FieldLog from "../../fieldLog/index.vue"
  import SchoolInfo from "../../school/schoolinfo/org_school.vue"
  import StudentInfo from "../../school/student/org_student.vue"
  import SelectAgent from "../agent/select.vue"
  import {
    isNumberStr
  } from '@/utils/index'
  import {
    getChangedFields
  } from '@/utils/formUtils'
  import {
    isEmpty
  } from "@/utils/validate"
  import {
    loadOptions
  } from "@/api/system/sys_region";

  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  export default {
    name: "Organization",
    dicts: ['common_state', 'level', 'org_type'],
    components: {
      SelectAgent,
      FieldLog,
      SchoolInfo,
      StudentInfo
    },
    data() {
      return {
        // 是否显示代理选择
        selectFlag: false,
        // 遮罩层
        loading: true,
        options: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 机构信息表格数据
        organizationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        detailView: false,
        submitLoading: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          contacts: null,
          organizationName: null,
          state: null,
          stuCount: null,
        },
        // 表单参数
        form: {
          level: [],
          orgType: null
        },
        // 表单校验
        rules: {
          contacts: [{
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }],
          organizationName: [{
            required: true,
            message: "机构名称不能为空",
            trigger: "blur"
          }],
          provinceAndCityAndDistrict: [{
            required: true,
            message: "省、市、区不能为空",
            trigger: "blur"
          }],
          stuCount: [{
            required: true,
            message: "招生人数不能为空",
            trigger: "blur"
          }],
          tel: [{
            required: true,
            message: "联系电话不能为空",
            trigger: "blur"
          }],
          address: [{
            required: true,
            message: "详细地址不能为空",
            trigger: "blur"
          }],
          state: [{
            required: true,
            message: "上线不能为空",
            trigger: "change"
          }],
          level: [{
            required: true,
            message: "级别不能为空",
            trigger: "change"
          }],
          orgType: [{
            required: true,
            message: "机构类型不能为空",
            trigger: "change"
          }],
          bookCount: [{
            required: true,
            message: "备课数不能为空",
            trigger: "blur"
          }],
          ratio: [{
            validator: (rule, value, callback) => {
              if (!isEmpty(value) && !isNumberStr(value)) {
                callback(new Error('佣金比例必须为数字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }],
          referencePrice: [{
            validator: (rule, value, callback) => {
              if (!isEmpty(value) && !isNumberStr(value)) {
                callback(new Error('参考价必须为数字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }]
        },
        //初始数据,用于比较
        originalData: {},
        // label 映射关系（手动维护）
        fieldLabels: {
          contacts: '联系人',
          organizationName: '机构名称',
          tel: '联系电话',
          state: '上线',
          stuCount: '招生人数',
          provinceAndCityAndDistrict: '省、市、区',
          agentName: '所属代理',
          address: '详细地址',
          firstSaleUser: '一销负责人',
          secondSaleUser: '二销负责人',
          ratio: '佣金比例',
          referencePrice: '参考价',
          level: '课程级别'
        },
      }
    },
    computed: {
      ...mapState({
        agent: state => state.selectAgent.agent,
        agentSelectModel: state => state.selectAgent.agentSelectModel
      })
    },
    created() {
      this.getList();
    },
    methods: {
      /**省 市 区*/
      selectLoadOptions(node, resolve) {
        var query = {
          regionLevel: node.level + 1,
          parentId: node.value || null
        }
        loadOptions(query).then(response => {
          resolve(response.data);
        });
      },
      /** 查询机构信息列表 */
      getList() {
        this.loading = true;
        listOrganization(this.queryParams).then(response => {
          this.organizationList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          contacts: null,
          organizationName: null,
          tel: null,
          province: null,
          city: null,
          district: null,
          address: null,
          state: null,
          stuCount: null,
          referencePrice: null,

          secondSaleUser: null,
          firstSaleUser: null,
          ratio: null,
          bookCount: null,
          level: [],
          orgType: null
        };
        this.resetForm("form");
        this.originalData = {}
        this.detailView = false
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加机构信息";
      },
      /** 选项卡按钮操作 */
      handleTabClick(tab, event) {
        const index = tab.index; // 当前点击的 tab 的索引（从 0 开始）
        if (0 == index) {
          this.loadTabData('student')
        } else if (1 == index) {
          this.loadTabData('school')
        } else if (2 == index) {
          this.loadTabData('fieldLog')
        }
      },
      /** 查看按钮操作 */
      handleDetail(row) {
        this.reset()
        const id = row.id || this.ids
        this.$nextTick(() => {
          getOrganization(id).then(response => {
            this.form = response.data
            this.open = true
            this.title = "查看机构信息"
            this.detailView = true
            this.$nextTick(() => {
              this.loadTabData('student')
            })
          }).catch(error => {
            console.error('获取机构详情失败:', error)
          })
        })
      },
      //加载数据
      loadTabData(tab) {
        let id = this.form.id
        if (tab == 'fieldLog') {
          const fieldLogRef = this.$refs.fieldLog
          if (fieldLogRef && typeof fieldLogRef.init === 'function') {
            fieldLogRef.init(id, 'ORG')
          } else {
            console.error('fieldLog 不存在或没有 init 方法')
          }
        } else if (tab == 'school') {
          const schoolInfoRef = this.$refs.schoolInfo
          if (schoolInfoRef && typeof schoolInfoRef.init === 'function') {
            schoolInfoRef.init(id)
          } else {
            console.error('schoolInfo 不存在或没有 init 方法')
          }
        } else if (tab == 'student') {
          const studentInfoRef = this.$refs.studentInfo
          if (studentInfoRef && typeof studentInfoRef.init === 'function') {
            studentInfoRef.init(id)
          } else {
            console.error('studentInfo 不存在或没有 init 方法')
          }
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getOrganization(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改机构信息";
          this.originalData = {
            ...response.data
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            let changedFieldsList = getChangedFields(
              this.originalData,
              this.form,
              this.fieldLabels
            )
            this.form.zzFormFieldChangeLogDTOList = changedFieldsList
            this.form.bookCount = this.form.orgType
            if (this.form.id != null) {
              updateOrganization(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addOrganization(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除机构信息编号为"' + ids + '"的数据项？').then(function() {
          return delOrganization(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('agent/organization/export', {
          ...this.queryParams
        }, `organization_${new Date().getTime()}.xlsx`)
      },
      //选择代理
      openSelectAgent(selectVal) {
        this.selectFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectAgent/cleanAgent')
        this.$store.dispatch('selectAgent/setAgentSelectModel', selectVal)
      },
      closeSelectAgent() {
        this.selectFlag = false
      },
      //确定代理
      selectAgentData() {
        this.closeSelectAgent()
        if (this.agentSelectModel == 2) {
          this.form.agentName = this.agent[0].agentName
          this.form.agentId = this.agent[0].id
          this.$refs.form.clearValidate(['agentName'])
        } else {
          this.queryParams.agentName = this.agent.map(item => item.agentName).join(',')
          this.queryParams.agentIdArray = this.agent.map(item => item.id)
        }
        this.$store.dispatch('selectAgent/cleanAgent')
      }
    }
  };
</script>
